<?php

namespace services;
use fast\Http;
class MeituanService{
    const AppID="wxde8ac0a21135c07d";
    const ID="gh_870576f3c6f9";
    const schema="imeituan://www.meituan.com/web?url=UrlEncode(targetUrl)";
    const AppKey="d0SrpQ8RJAkRYWAi";
    const utmSource="324677";
    const version="2.0";
    protected $method='AES-128-ECB';
    protected $aes_options=0;
    protected $iv='';
    protected $is_hex=true;   // 要求输出格式为HEX
    protected $accessToken = null;
    protected $timestamp = null;
    public $requestId = null;
    public $activity = null; // 活动ID (从分销联盟后台--【我要推广】中获取)
    public $promotionId = null;  // 推广位ID (在分销联盟后台创建生成)
    public $pageLevel = 2;  // 页面分销层级 (详见PageLevelEnum)
    public $userLevel = 1;  // 渠道用户等级，用于处理页面展示佣金信息，一般在二级分销页面需要传递。默认为1，请求值需要在0-1之间，例如:0.8
    public $demandQrInfo = false;  // 是否需要返回二维码，默认为false。一般在微信二级分销场景下需要，请渠道结合实际情况使用该字段，返回二维码可能会导致接口响应时间变长，取链失败等情况。
    public $url = null;


    // 美团官方
    public $phone = null;
    public $p = null;
    public $mediaPvid = null;
    public $mturl = null;

    public function __construct($activity,$promotionId){
        $this->timestamp = time();
        $this->accessToken = $this->setAccessToken();
        $this->activity = $activity;
        $this->promotionId = $promotionId;

        $this->phone='18072725357';
        $this->p='278e77b616ab4bd3a88bd3a3b21653f4';
        $this->mediaPvid='8ba6eeedf4a74c1f9975ac6e0863326c';
        $this->mturl = 'https://offsiteact.meituan.com/';
    }


    
    /**
     * 活动取链
     * @DateTime 2023-04-18T14:24:51+0800
     * @param    [type]                   $requestId 请求Id，媒体方生成，不超过32位
     * @param    [type]                   $utmMedium 二级渠道标识（必须AES加密）
     * @return   [type]                              [description]
     */
    //{"code ":200,"msg ":"success ","data ":{"activity ":"mZAV9n2ekN ","commonLink ":"https: //click.meituan.com/t?t=1&c=2&p=pZzXYL5zKBil","shortLink":"http://dpurl.cn/RJSE16Az","commonQrCode":"","miniProgramPath":"/index/pages/h5/h5?f_userId=1&f_token=1&s_cps=0&weburl=https%3A%2F%2Fdpurl.cn%2FRJSE16Az","miniProgramPathForCommon":"/index/pages/h5/h5?f_userId=1&f_token=1&s_cps=0&weburl=https%3A%2F%2Fclick.meituan.com%2Ft%3Ft%3D1%26c%3D2%26p%3DpZzXYL5zKBil","miniProgramQrCode":"","materialDownloadLink":"https://mss-shon.sankuai.com/cps-bucket/%E9%AB%98%E4%BD%A3%E4%BC%9A%E5%9C%BA%E7%B4%A0%E6%9D%90.zip?AWSAccessKeyId=9f36d233a9434e10bc3e2dde9f327f02&Expires=1681827948&Signature=vtNzJkV8Lfmb8pSQ8%2BYHv1JxaXc%3D","deepLink":"imeituan://www.meituan.com/takeout/browser?inner_url=https%3A%2F%2Fclick.meituan.com%2Ft%3Ft%3D1%26c%3D2%26p%3DpZzXYL5zKBil&lch=cps:fxlmwm:0:growth:deeplink:0:324677","beginTime":1669737600,"endTime":1704038399,"ruleInfo":""},"serverTrackId":"5421404402494978831"}
    public function getActivityLink($requestId,$utmMedium)
    {
        $this->url = 'https://union.dianping.com/api/promotion/link';
        $query = [
          'requestId' => $requestId,
          'utmSource' => self::utmSource,
          'version' => self::version,
          'accessToken' => $this->accessToken,
          'timestamp' => $this->timestamp,
        ];
        $param = [
          'utmSource' => self::utmSource,
          'utmMedium' => $this->encrypt($utmMedium),
          'activity' => $this->activity,
          'promotionId' => $this->promotionId,
          'pageLevel' => $this->pageLevel,
          'userLevel' => $this->userLevel,
          'demandQrInfo' => $this->demandQrInfo,
        ];
        $sign = $this->sign($query, $param);
        // $query['signMethod'] = 'hmac';
        // $query['sign'] = strtoupper($sign);
        $url = $this->url.'?'.http_build_query($query);
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($url,$params,[],$header);
    }

    // accessToken
    public function setAccessToken()
    {
        return $this->encrypt(self::utmSource.$this->timestamp);
    }

    // aes加密
    public function encrypt($data,$key='')
    {
        empty($key) && $key=self::AppKey;
        $base64=openssl_encrypt($data, $this->method, $key, $this->aes_options, $this->iv);
        return $this->is_hex ? bin2hex(base64_decode($base64)) : $base64;
    }

    // 签名
    public function sign($query, $param)
    {
      $param = array_merge($param,$query);
      ksort($param);
      $md5str = '';
      foreach ($param as $key => $value) {
        $md5str .= $key.$value;
      }
      $sign = hash_hmac('md5', $md5str, self::AppKey);
      return $sign;
    }


    /**
     * cps订单
     * @DateTime 2023-05-05T09:47:48+0800
     * @param    [type]                   $requestId [description]
     * @return   [type]                              [description]
     */
    public function getCpsOrderList1($param, $requestId)
    {
        $this->url = "https://union.dianping.com/data/promote/verify/item";
        $query = [
          'requestId' => $requestId,
          'utmSource' => self::utmSource,
          'version' => self::version,
          'accessToken' => $this->accessToken,
          'timestamp' => $this->timestamp,
        ];
        $sign = $this->sign($query, $param);
        // $query['signMethod'] = 'hmac';
        // $query['sign'] = strtoupper($sign);
        $url = $this->url.'?'.http_build_query($query);
        $header = [];
        return Http::get($url,$param,[],$header);
    }


    /**
     * 2024-07-12新版美团cps订单
     * @DateTime 2023-05-05T09:47:48+0800
     * @param    [type]                   $requestId [description]
     * @return   [type]                              [description]
     * {"code":0,"message":"成功","data":{"actId":null,"skuCount":100,"scrollId":"","code":0,"msg":"成功","dataList":[{"businessLine":1,"orderId":"301158592603123093","payTime":1720850070,"payPrice":"25.00","updateTime":1720853608,"commissionRate":"10","profit":"0.03","cpaProfit":"0","sid":"4686188","productId":"null","productName":"悦容汤|燕窝.苏式绿豆汤.桃胶炖奶（第A13档口店）","orderDetail":null,"refundPrice":null,"refundTime":"null","refundProfit":"null","cpaRefundProfit":"0","status":"3","tradeType":1,"actId":7,"appkey":"350a85b1120840f2bf7ea678a57a987f","skuCount":null,"platform":1,"cityName":null}]}}
     */
    public function getCpsOrderList($param, $requestId)
    {
        $time = time();
        $microtime = $time*1000;
        $appkey=$this->activity;
        $appsecret=$this->promotionId;
        $url = "https://media.meituan.com/cps_open/common/api/v1/query_order";
        $params = json_encode($param,1);
        // $params=mb_convert_encoding($params, 'UTF-8', 'auto');
        $Content_MD5=base64_encode(md5($params,true));
        $signHeaders = [
            'S-Ca-App' => $appkey,
            'S-Ca-Timestamp' => (string) $microtime,
            'S-Ca-Signature-Headers' => 'S-Ca-App,S-Ca-Timestamp',
            'Content-MD5' => $Content_MD5,
        ];
        $path = '/' . implode('/', array_slice(explode('/', $url), 3));
        $strSign = sprintf(
            "%s\n%s\n%s%s",
            'POST',
            $Content_MD5,
            self::headers($signHeaders),
            $path
        );
        $hash = hash_hmac('sha256', $strSign, $appsecret, true);
        $signHeaders['S-Ca-Signature'] = base64_encode($hash);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        foreach ($signHeaders as $key => $value) {
            $header[] = $key.':'.$value;
        }
        return Http::post($url,$params,[],$header);
    }

    /**
     * 签名计算Header的Key拼接
     * @param array $signHeaders
     * @return string
     */
    public static function headers($signHeaders)
    {
        $str = '';
        ksort($signHeaders);
        $sortData = $signHeaders;
        $list = array_filter(array_keys($sortData), function ($key) {
            return $key !== 'S-Ca-Signature-Headers' && $key !== 'Content-MD5';
        });

        foreach ($list as $key) {
            $value = $sortData[$key];
            $str .= sprintf('%s:%s' . "\n", $key, $value ?? '');
        }

        return $str;
    }


    /**
     * cps订单
     * @DateTime 2023-05-05T09:47:48+0800
     * @param    [type]                   $requestId [description]
     * @return   [type]                              [description]
     */
    public function getCpaOrderList($param, $requestId)
    {
        $this->url = "https://union.dianping.com/data/promote/verify/cpa";
        $query = [
          'requestId' => $requestId,
          'utmSource' => self::utmSource,
          'version' => self::version,
          'accessToken' => $this->accessToken,
          'timestamp' => $this->timestamp,
        ];
        $param = [
          'page' => 1,
          'size' => 20,
        ];
        $sign = $this->sign($query, $param);
        // $query['signMethod'] = 'hmac';
        // $query['sign'] = strtoupper($sign);
        $url = $this->url.'?'.http_build_query($query);
        $header = [];
        return Http::get($url,$param,[],$header);
    }


    public function offsiteactList($lat,$lon,$pagePvId='',$searchWord='')
    {
        $url = $this->mturl.'act/cpsapi/get_list_v3';
        $param = [
          'p' => $this->p,
          'mediaPvid' => $this->mediaPvid,
          'lat' => $lat,
          'lon' => $lon,
          'mediaUserid' => '',
          'sortType' => 1,//请求活动商家列表排序类型枚举
          'pagePvId' => $pagePvId,
          // 'categoryTypeList' => [],
        ];
        if ($searchWord) {
          $param['searchWord'] = $searchWord;
        }
        $key = substr($param['p'],0,16);
        $param['mediaUserid'] = base64_encode(openssl_encrypt($this->phone, 'AES-128-CBC', $key, OPENSSL_RAW_DATA,$key));
        $param['DeviceIdInfo'] = [
          'id' => '',
          'device_id_type' => 4,
        ];
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($url,$params,[],$header);
    }


    /**
     * 报名
     * @param  string $value [description]
     * @return [type]        [description]
     * {"status":true,"code":0,"msg":"SUCCESS","data":{"userEventId":"sn0YdKDxZr7rES79euaV7w==","platform_order_no":"BWC202308092038429639833"}}
     */
    public function registerevent($lng,$lat,$poiEventId,$meituanPvId,$telephone,$ip)
    {
        $url = $this->mturl.'act/cpsapi/registerevent';
        $param = [
          'p' => $this->p,
          'mediaUserId' => '',
          'poiEventId' => $poiEventId,
          'meituanPvId' => $meituanPvId,
          'actualLongitude' => $lng,
          'actualLatitude' => $lat,
          'clientIp' => $ip,
          'cashBackMode' => 0,//⽤户返现⽅式：⽀持独⽴返现、统⼀返现两种模式。0-独⽴返现,1-统⼀返现
          // 'subsidyRatio' => '',//渠道补贴⽐例：渠道愿意从⾃⾝结佣中拿出多少补给⽤户。(统⼀返现，特有字段)渠道补贴⾦额 = 补贴⽐例*渠道佣⾦⽐例*⽤户实付单位：1/10000 (550 代表 550/10000 = 补贴 5.5%)默认为 0，补贴⽐例最⼤为渠道结佣的 100%即补贴范围：[0, 10000] = [0%,100%]
        ];
        $key = substr($param['p'],0,16);
        $param['mediaUserId'] = base64_encode(openssl_encrypt($telephone, 'AES-128-CBC', $key, OPENSSL_RAW_DATA,$key));
        \think\Log::write('美团官方报名'.json_encode($param).$url);
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($url,$params,[],$header);
    }


    /**
     * 取消报名
     * @param  string $value [description]
     * @return [type]        [description]
     * {"status":true,"code":0,"msg":"SUCCESS","data":{}}
     */
    public function cancelevent($telephone,$userEventId)
    {
        $url = $this->mturl.'act/cpsapi/cancelevent';
        $param = [
          'p' => $this->p,
          'mediaUserId' => '',
          'userEventId' => $userEventId,
        ];
        $key = substr($param['p'],0,16);
        $param['mediaUserId'] = base64_encode(openssl_encrypt($telephone, 'AES-128-CBC', $key, OPENSSL_RAW_DATA,$key));
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($url,$params,[],$header);
    }


    /**
     * 对账单
     * @param  string $value [description]
     * @return [type]        [description]
     * {"status":true,"code":0,"msg":"SUCCESS","data":{}}
     */
    public function loadorder($time)
    {
        $url = $this->mturl.'act/cpsapi/load_order';
        $param = [
          'p' => $this->p,
          'startTime' => $time,
        ];
        $params = json_encode($param);
        $header = array('Content-Type: application/json; charset=utf-8','Content-Length:' . strlen($params));
        return Http::post($url,$params,[],$header);
    }

}
